﻿namespace ChangchunPulbicServicesImp;

public class AuxiliaryFunctionServices : IAuxiliaryFunction
{
    public IUserAccountServices UserAccountServices { get; set; }

    public IDraftServices DraftServices { get; set; }

    public IAnnotationServices AnnotationServices { get; set; }

    private IHttpClientFactory HttpClientFactory { get; init; }

    private IConfigServices ConfigServices { get; init; }

    public AuxiliaryFunctionServices(IUserAccountServices userAccountServices, IDraftServices draftServices, IAnnotationServices annotationServices, IHttpClientFactory httpClientFactory, IConfigServices configServices)

    {
        UserAccountServices = userAccountServices;
        DraftServices = draftServices;
        AnnotationServices = annotationServices;
        HttpClientFactory = httpClientFactory;
        ConfigServices = configServices;
    }

    public async Task<CreateUserDraftResult> CreateUserDraftAsync(User user, Draft draft)
    {
        ///验证用户信息
        var loginResult = await UserAccountServices.LoginAsync(user);
        if (!loginResult.Succeed)
            return new CreateUserDraftResult()
            {
                StatusCode = Code.WrongValidation,
                Message = $"用户验证失败，详情：{loginResult.Message}",
            };

        ///创建标绘
        var addResult = await DraftServices.AddDraftAsync(draft);
        if (!addResult.Succeed)
            return new CreateUserDraftResult()
            {
                StatusCode = addResult.StatusCode,
                Message = $"为用户创建Draft失败，详情：{addResult.Message}",
                SourceException = addResult.SourceException
            };

        ///创建成功
        return new CreateUserDraftResult()
        {
            StatusCode = Code.Succeed,
            Message = "为用户创建Draft成功",
            NewKey = addResult.NewKey,
        };
    }

    public async Task<DeleteUserDraftResult> DeleteUserDraftAsync(User user, int draftID)
    {
        ///验证用户信息
        var loginResult = await UserAccountServices.LoginAsync(user);
        if (!loginResult.Succeed)
            return new DeleteUserDraftResult()
            {
                StatusCode = Code.WrongValidation,
                Message = $"用户验证失败，详情：{loginResult.Message}",
            };

        ///删除用户标绘
        var delResult=await DraftServices.DeleteDraftAsync(draftID);
        if (!delResult.Succeed)
            return new DeleteUserDraftResult()
            {
                StatusCode = delResult.StatusCode,
                Message = $"为用户删除Draft失败，详情：{delResult.Message}",
                SourceException = delResult.SourceException
            };

        ///创建成功
        return new DeleteUserDraftResult()
        {
            StatusCode = Code.Succeed,
            Message = "为用户删除Draft成功",
        };
    }

    public async Task<GetUserDraftResult> QueryDeepCopyOf(int draftID, User user)
    {
        ///验证用户信息
        var loginResult = await UserAccountServices.LoginAsync(user);
        if (!loginResult.Succeed)
            return new GetUserDraftResult()
            {
                StatusCode = Code.WrongValidation,
                Message = $"用户验证失败，详情：{loginResult.Message}",
            };

        ///获取标绘的深拷贝
        var queryResult = await DraftServices.GetDeepCopyOf(draftID);
        if(!queryResult.Succeed)
            return new GetUserDraftResult()
            {
                StatusCode = queryResult.StatusCode,
                Message = $"为用户获取Draft失败，详情：{queryResult.Message}",
                SourceException=queryResult.SourceException,
            };

        return new GetUserDraftResult()
        {
            StatusCode = Code.Succeed,
            Message = "为用户获取Draft成功",
            UserDraft = queryResult.ResultObject,
        };
    }

    public async Task<GetUserDraftResult> QueryUserDraftAsync(User user, int draftID)
    {
        ///验证用户信息
        var loginResult = await UserAccountServices.LoginAsync(user);
        if (!loginResult.Succeed)
            return new GetUserDraftResult()
            {
                StatusCode = Code.WrongValidation,
                Message = $"用户验证失败，详情：{loginResult.Message}",
            };

        ///获取标绘的浅拷贝
        var queryResult = await DraftServices.GetDraftAsync(draftID);
        if (!queryResult.Succeed)
            return new GetUserDraftResult()
            {
                StatusCode = queryResult.StatusCode,
                Message = $"为用户获取Draft失败，详情：{queryResult.Message}",
                SourceException = queryResult.SourceException,
            };

        return new GetUserDraftResult()
        {
            StatusCode = Code.Succeed,
            Message = "为用户获取Draft成功",
            UserDraft = queryResult.ResultObject,
        };
    }

    public async Task<QueryUserDraftListResult> QueryUserDraftListAsync(User user)
    {
        ///验证用户信息
        var loginResult = await UserAccountServices.LoginAsync(user);
        if (!loginResult.Succeed)
            return new QueryUserDraftListResult()
            {
                StatusCode = Code.WrongValidation,
                Message = $"用户验证失败，详情：{loginResult.Message}",
            };

        var queryResult = await DraftServices.GetRelativeDraftsAsync(user.Account);
        if (!queryResult.Succeed)
            return new QueryUserDraftListResult()
            {
                StatusCode = queryResult.StatusCode,
                Message = $"为用户获取Drafts失败，详情：{queryResult.Message}",
                SourceException = queryResult.SourceException,
            };

        return new QueryUserDraftListResult()
        {
            StatusCode = Code.Succeed,
            Message = $"为用户获取Drafts成功",
            DraftList = queryResult.ResultObject,
        };
    }

    public async Task<UpdateUserDraftResult> UpdateUserDraftAsync(User user, Draft draft)
    {
        ///验证用户信息
        var loginResult = await UserAccountServices.LoginAsync(user);
        if (!loginResult.Succeed)
            return new UpdateUserDraftResult()
            {
                StatusCode = Code.WrongValidation,
                Message = $"用户验证失败，详情：{loginResult.Message}",
            };

        var updateResult = await DraftServices.UpdateDraftsAsync(draft);
        if (!updateResult.Succeed)
            return new UpdateUserDraftResult()
            {
                StatusCode = updateResult.StatusCode,
                Message = $"为用户更新Draft失败，详情：{updateResult.Message}",
                SourceException = updateResult.SourceException,
            };

        return new UpdateUserDraftResult()
        {
            StatusCode = Code.Succeed,
            Message = $"为用户更新Draft成功",
            NewKey = updateResult.NewKey
        };
    }

    public async Task<WeatherForecastResult> WeatherForecastAsync(Point location)
    {
        var transResult = await GeoTransfer(location);
        if (!transResult.Succeed)
            return new()
            {
                StatusCode = transResult.StatusCode,
                Message = "坐标转换失败",
            };

        var handledLocaiton = transResult.ResultCoordinate;

        if (handledLocaiton is null) 
            return new ()
            {
                StatusCode = Code.InternalFault,
                Message = "解析结果时出现空引用",
            };

        ///请求API
        var client = HttpClientFactory.CreateClient();
        client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");
        var apiResult = await APIHelper.GetAsync<Weather>(client,
            $"https://data.cma.cn/dataGis/multiSource/getAPILiveDataInfo?lat={handledLocaiton.lat}&lon={handledLocaiton.lng}");

        ///查询失败
        if (!apiResult.Succeed)
            return new ()
            {
                StatusCode = apiResult.StatusCode,
                Message = "查询失败",
                QueryResultFrom3rdPartyApi = apiResult,
            };

        if (apiResult.ResultObject is null)
            return new()
            {
                StatusCode = Code.InternalFault,
                Message = "解析结果时出现空引用",
                QueryResultFrom3rdPartyApi = apiResult,
            };

        return new()
        {
            StatusCode = Code.Succeed,
            Message = "查询成功",
            QueryResultFrom3rdPartyApi = apiResult,
        };
    }

    public async Task<GeoCoordinateTransResult> GeoTransfer(Point location)
    {
        //请求API
        var client = HttpClientFactory.CreateClient();
        var apiResult = await APIHelper.GetAsync<GeoTrans>(client,
            $"https://api.map.baidu.com/geoconv/v1/?coords={location.ToCoordinate()}&from=3&to=5&ak={ConfigServices.AK}");

        //查询失败
        if (!apiResult.Succeed)
            return new()
            {
                StatusCode = apiResult.StatusCode,
                Message = "查询失败",
                QueryResultFrom3rdPartyApi = apiResult,
            };

        var result = apiResult.ResultObject?.HandledResult;
        if (result is null)
            return new()
            {
                StatusCode = Code.InternalFault,
                Message = "解析查询结果时，程序发生内部错误",
                QueryResultFrom3rdPartyApi = apiResult,
            };

        return new()
        {
            StatusCode = Code.Succeed,
            Message = "查询成功",
            QueryResultFrom3rdPartyApi = apiResult
        };
    }
}